/*
 * Copyright (c) 2008-2011, Petr Panteleyev
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 *    1. Redistributions of source code must retain the above copyright notice,
 *       this list of conditions and the following disclaimer.
 *    2. Redistributions in binary form must reproduce the above copyright notice,
 *       this list of conditions and the following disclaimer in the documentation
 *       and/or other materials provided with the distribution.
 *    3. The name of the author may not be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package org.panteleyev.gclient;

import java.awt.Dimension;
import java.io.File;

import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import org.jdesktop.swingx.JXBusyLabel;

import org.panteleyev.swing.BasicDialog;
import org.panteleyev.swing.OkCancelButtonPanel;
import org.panteleyev.swing.filefilters.ImageFileFilter;

/**
 *
 * @author Petr Panteleyev
 */
final class GBPostPictureDialog extends BasicDialog<GBEditorFrame> {
    private GBUserProfile profile;
    private GBAccount account;

    private AbstractAction choosePhotoAction;
    private AbstractAction fullSizeAction;
    private AbstractAction reducedSizeAction;

    private GPhoto photo;

    public GBPostPictureDialog(GBEditorFrame parent, GBUserProfile profile) {
        super(parent);

        this.profile = profile;
        this.account = profile.getAccount();

        createActions();
        initComponents();

        fullSizeRadioButton.setSelected(true);
        enableSizeControls(false);

        pack();
    }

    public GBUserProfile getProfile() {
        return profile;
    }
    public GPhoto getPhoto() {
        return photo;
    }

    private void createActions() {
        choosePhotoAction = new AbstractAction("...", null) {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                onChoosePhoto();
            }
        };

        fullSizeAction = new AbstractAction(L10N.PPD_FULL_SIZE_RADIO.s(), null) {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                enableSizeControls(false);
            }
        };

        reducedSizeAction = new AbstractAction(L10N.PPD_REDUCED_SIZE_RADIO.s(), null) {
            @Override
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                enableSizeControls(true);
            }
        };
    }

    private void onChoosePhoto() {
        JFileChooser dial = new JFileChooser();
        dial.setAcceptAllFileFilterUsed(false);
        dial.setDialogTitle("Upload Photo");
        dial.setMultiSelectionEnabled(false);

        dial.addChoosableFileFilter(new ImageFileFilter());

        if (dial.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            photoPathEdit.setText(dial.getSelectedFile().getPath());
        }
    }

    boolean getFullSize() {
        return fullSizeRadioButton.isSelected();
    }

    boolean getLinkToSource() {
        return linkToOriginalCheckBox.isSelected();
    }

    int getSmallSizeIndex() {
        return sizeComboBox.getSelectedIndex();
    }

    private void enableSizeControls(boolean enable) {
        sizeComboBox.setEnabled(enable);
        linkToOriginalCheckBox.setEnabled(enable);
    }

    boolean getImageBorder() { return imgBorderCheckBox.isSelected(); }

    @Override
    protected void onOk() {
        String path = photoPathEdit.getText();
        if (path.length() == 0) {
            return;
        }

        final File file = new File(path);

        int albumIndex = albumList.getSelectedIndex();
        final GAlbum album = account.getAlbum(albumIndex);
        if (album == null) {
            return;
        }

        Thread thread = new Thread() {
            @Override
            public void run() {
                try {
                    busyLabel.setBusy(true);
                    photo = account.uploadPhoto(album, file);
                    getProfile().sendApplicationEvent(new AlbumFhotosUpdateEvent(this, album));
                    GBPostPictureDialog.super.onOk();
                } catch (GBException e) {
                    onCancel();
                    // TODO: handle this properly
                } finally {
                    // TODO: close status bar here
                }
            }
        };

        choosePhotoButton.setEnabled(false);
        okCancelPanel.enableButtons(false);
        thread.start();
    }

    private JTextField          photoPathEdit;
    private JButton             choosePhotoButton;
    private JComboBox           albumList;
    private JRadioButton        fullSizeRadioButton;
    private JRadioButton        reducedSizeRadioButton;
    private JComboBox<Integer>  sizeComboBox;
    private JCheckBox           linkToOriginalCheckBox;
    private JCheckBox           imgBorderCheckBox;
    private OkCancelButtonPanel okCancelPanel;
    private JXBusyLabel         busyLabel;

    private void initComponents() {
        setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(L10N.PPD_TITLE.s());
        setResizable(false);
        getContentPane().setLayout(new BoxLayout(getContentPane(), BoxLayout.PAGE_AXIS));

        photoPathEdit = new JTextField(20);
        choosePhotoButton = new JButton(choosePhotoAction);

        /* Photo path panel */
        JPanel uploadPanel = new JPanel();
        uploadPanel.setAlignmentX(JComponent.LEFT_ALIGNMENT);
        uploadPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        uploadPanel.setLayout(new BoxLayout(uploadPanel, BoxLayout.LINE_AXIS));
        uploadPanel.add(photoPathEdit);
        uploadPanel.add(Box.createHorizontalStrut(3));
        uploadPanel.add(choosePhotoButton);
        uploadPanel.add(Box.createHorizontalStrut(3));
        uploadPanel.add(busyLabel = new JXBusyLabel(new Dimension(16,16)));
        getContentPane().add(uploadPanel);

        /* Album panel */
        JPanel albumPanel = new JPanel();
        albumPanel.setAlignmentX(JComponent.LEFT_ALIGNMENT);
        albumPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        albumPanel.setLayout(new BoxLayout(albumPanel, BoxLayout.LINE_AXIS));
        albumPanel.add(new JLabel(L10N.PPD_ALBUM_LIST_LABEL.s()));
        albumPanel.add(Box.createHorizontalStrut(3));
        albumList = new GBAlbumComboBox(account);
        albumPanel.add(albumList);
        albumPanel.add(Box.createHorizontalGlue());
        getContentPane().add(albumPanel);

        /* Link Panel */
        JPanel linkPanel = new JPanel();
        linkPanel.setAlignmentX(JComponent.LEFT_ALIGNMENT);
        linkPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        linkPanel.setLayout(new BoxLayout(linkPanel, BoxLayout.PAGE_AXIS));

        ButtonGroup group = new ButtonGroup();

        fullSizeRadioButton = new JRadioButton(fullSizeAction);
        fullSizeRadioButton.setAlignmentX(JComponent.LEFT_ALIGNMENT);
        group.add(fullSizeRadioButton);
        linkPanel.add(fullSizeRadioButton);

        JPanel subPanel = new JPanel();
        subPanel.setAlignmentX(JComponent.LEFT_ALIGNMENT);
        subPanel.setLayout(new BoxLayout(subPanel, BoxLayout.LINE_AXIS));

        reducedSizeRadioButton = new JRadioButton(reducedSizeAction);
        group.add(reducedSizeRadioButton);
        subPanel.add(reducedSizeRadioButton);

        sizeComboBox = new JComboBox<>(new Integer[] { 72, 144, 288 });
        subPanel.add(sizeComboBox);
        subPanel.add(Box.createHorizontalGlue());

        linkPanel.add(subPanel);

        linkToOriginalCheckBox = new JCheckBox(L10N.PPD_LINK_TO_ORIGINAL_CHECK.s());
        linkToOriginalCheckBox.setAlignmentX(JComponent.LEFT_ALIGNMENT);
        linkPanel.add(linkToOriginalCheckBox);

        imgBorderCheckBox = new JCheckBox(L10N.PPD_IMAGE_BORDER_CHECK.s());
        imgBorderCheckBox.setAlignmentX(JComponent.LEFT_ALIGNMENT);
        linkPanel.add(imgBorderCheckBox);

        getContentPane().add(linkPanel);
        getContentPane().add(okCancelPanel = new OkCancelButtonPanel(this, JComponent.LEFT_ALIGNMENT));

        pack();
    }
}
